package com.ruoyi.product.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.product.domain.*;
import com.ruoyi.product.domain.vo.ProductAll;
import com.ruoyi.product.domain.vo.ShopProductVo;
import com.ruoyi.product.mapper.*;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.product.service.IProductService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * 商品Service业务层处理
 *

 * @date 2023-07-20
 */
@Service
public class ProductServiceImpl implements IProductService
{
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private CategoriesMapper categoriesMapper;

    /**
     * 查询商品
     *
     * @param proId 商品主键
     * @return 商品
     */
    @Override
    public Product selectProductByProId(Long proId)
    {
        return productMapper.selectProductByProId(proId);
    }
    /**
     * 查询商品 级联
     *
     * @param proId 商品主键
     * @return 商品
     */
    @Override
    public Product getProductByProId(Long proId) {
        return productMapper.getProductByProId(proId);
    }

    /**
     * 查询商品列表
     *
     * @param product 商品
     * @return 商品
     */
    @Override
    public List<Product> selectByAll(Product product)
    {
        return productMapper.selectByAll(product);
    }

    @Override
    public List<ShopProductVo> queryWithShopId(Long shopId) {
        Product product = new Product();
        product.setShopId(shopId);
        List<Product> products = productMapper.selectAllWithDetail(product);

        List<ShopProductVo> data = new ArrayList<>();
        Categories categories = new Categories();
        categories.setParentId(0L);
        List<Categories> cg1 = categoriesMapper.selectCategoriesList(categories);

        for (Categories categories1 : cg1) {
            List<Product> collect = new ArrayList<>();
            products.forEach((item)->{
                String[] split = item.getCategory().split("/");
                Long cgId = Long.parseLong(split[0]);
                if (Objects.equals(cgId, categories1.getId())) {
                    collect.add(item);
                }
            });
            if (collect.size()!=0) {
                ShopProductVo vo = new ShopProductVo();
                vo.setCategoryName(categories1.getName());
                vo.setProducts(collect);
                data.add(vo);
            }
        }
        return data;
    }

    /**
     * 新增商品
     *
     * @param product 商品
     * @return 结果
     */
    @Override
    public int insertProduct(Product product)
    {
        LoginUser loginUser = tokenService.getLoginUser();
        System.out.println(loginUser);
        product.setCreateBy(loginUser.getUsername());
        product.setCreateTime(DateUtils.getNowDate());
        return productMapper.insertProduct(product);
    }

    /**
     * 聚合增加
     *
     *
     * @param productAll 商品
     * @return 结果
     */
    @Resource
    private DetailMapper detailMapper;
    @Resource
    private ArgsMapper argsMapper;
    @Resource
    private ProdImageMapper prodImageMapper;
    @Override
    @Transactional
    public long addProductAll(ProductAll productAll)
    {
        LoginUser loginUser = tokenService.getLoginUser();
        System.out.println(loginUser);
        long id = 0;
        // 商品表
        Product product = productAll.product();
        if (product.getProId()==null) {
            productAll.product().setCreateBy(loginUser.getUsername());
            productAll.product().setCreateTime(DateUtils.getNowDate());
            productMapper.insertProduct(product);
            id = product.getProId();
        } else {
            id = product.getProId();
            productMapper.updateProduct(product);
        }
        // 删除详情表的所有数据
        Detail d = new Detail();
        d.setProductId(id);
        List<Detail> ds = detailMapper.selectDetailList(d);
        ds.forEach(o->detailMapper.deleteDetailById(o.getId()));
        // 更新详情表
        Detail detail = productAll.detail();
        detail.setProductId(id);
        detailMapper.insertDetail(detail);

        // 删除参数表的所有数据
          // 先从中间表里面找到所有的参数
        List<Args> allByProId = argsMapper.getAllByProId(id);
          // 删除中间表数据
        argsMapper.deleteProductArgs(id);
        allByProId.forEach(o->argsMapper.deleteArgsById(o.getId()));
        // 参数表
        List<Args> args = productAll.args();
          // 首先得到父id为0的参数
        long pId = 0;
        for (Args af : args) {
            long pi = 0;
            System.out.println(af);
            if (af != null && af.getParentId()!= null && af.getParentId()==0){
                argsMapper.insertArgs(af);
                pi = af.getId();
                pId = pi;
                // 修改中间表
                argsMapper.insertProductArgs(id, pi);
            } else {
                assert af != null;
                af.setParentId(pId);
                argsMapper.insertArgs(af);
            }
        }
        // 图片表
        ProdImage p = new ProdImage();
        p.setProductId(id);
        List<ProdImage> ps = prodImageMapper.selectProdImageList(p);
        ps.forEach(o->prodImageMapper.deleteProdImageById(o.getId()));
        List<ProdImage> prodImages = productAll.prodImage();
        for (ProdImage prodImage : prodImages) {
            prodImage.setProductId(id);
            prodImageMapper.insertProdImage(prodImage);
        }
        return id;
    }


    /**
     * 修改商品
     *
     * @param product 商品
     * @return 结果
     */
    @Override
    public int updateProduct(Product product)
    {
        LoginUser loginUser = tokenService.getLoginUser();
        System.out.println(loginUser);
        product.setUpdateBy(loginUser.getUsername());
        product.setUpdateTime(DateUtils.getNowDate());
        return productMapper.updateProduct(product);
    }

    /**
     * 批量删除商品
     *
     * @param proIds 需要删除的商品主键
     * @return 结果
     */
    @Override
    public int deleteProductByProIds(Long[] proIds)
    {
        return productMapper.deleteProductByProIds(proIds);
    }

    /**
     * 删除商品信息
     *
     * @param proId 商品主键
     * @return 结果
     */
    @Override
    public int deleteProductByProId(Long proId)
    {
        return productMapper.deleteProductByProId(proId);
    }
}
